package com.tegtech.module.captcha.service.impl;

import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.tegtech.common.exception.BusinessExceptionUtil;
import com.tegtech.common.function.Procedure;
import com.tegtech.module.captcha.cache.CaptchaCache;
import com.tegtech.module.captcha.constant.CaptchaKey;
import com.tegtech.module.captcha.domain.CaptchaRule;
import com.tegtech.module.captcha.enums.CaptchaHttpStatus;
import com.tegtech.module.captcha.service.ICaptchaValidateService;

import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.StrUtil;

@Service
public class CaptchaValidateServiceImpl implements ICaptchaValidateService {

	@Autowired
	protected CaptchaCache captchaCache;
	
	@Override
	public void validateCaptcha(String account, String code, CaptchaRule captchaRule) {
		Map<String, Object> map = captchaCache.getCodeMap(account, captchaRule.getKey());
		String oldCode = MapUtil.getStr(map, CaptchaKey.CAPTCHA_CODE);
		if (StrUtil.isBlank(oldCode)) {
			BusinessExceptionUtil.i18nEx(CaptchaHttpStatus.CAPTCHA_EXPIRE);
		}
		if (!StrUtil.equals(code, oldCode)) {
			BusinessExceptionUtil.i18nEx(CaptchaHttpStatus.CAPTCHA_INVALID);
		}
	}

	@Override
	public void clearCaptcha(String account, CaptchaRule captchaRule) {
		captchaCache.clearCode(account, captchaRule.getKey());
	}

	@Override
	public void validateAndClearCaptcha(String account, String code, CaptchaRule captchaRule, Procedure procedure) {
		// 校验验证码
		validateCaptcha(account, code, captchaRule);
		// 执行校验通过后的逻辑
		procedure.run();
		// 清除验证码
		clearCaptcha(account, captchaRule);
	}

}
